import { localCache } from '@/utils/cache'
import { firstMenu } from '@/utils/mapmenu'
import { notification } from '@/utils/notification'
import { closeNprogress, openNprogress } from '@/utils/nprogress'
import { TOKEN } from '@/utils/token'
import { createRouter, createWebHashHistory } from 'vue-router'

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    { path: '/', redirect: 'main' },
    { path: '/login', component: () => import('@/views/login/login.vue') },
    { path: '/main', name: 'main', component: () => import('@/views/main/main.vue') },
    { path: '/:pathMatch(.*)*', component: () => import('@/views/404/404.vue') }
  ]
})

// 前置路由守卫
router.beforeEach((to) => {
  // 路由跳转打开loading
  openNprogress()
  const token = localCache.getCache(TOKEN)
  // 如果进入到main相关页面并且没有登录，则让用户返回登录。
  if (to.path.startsWith('/main') && !token) {
    // notification('warning', '请先完成账号登录')
    return '/login'
  }

  // 如果进入到main页面，默认打开第一个页面
  if (to.path === '/main') {
    return firstMenu
  }
})

// 后置路由守卫
router.afterEach(() => {
  // 路由跳转完成关闭loading
  closeNprogress()
})

export default router
